package com.tanhua.server.service;

import com.tanhua.commons.pojo.IMessage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLocationDTO;
import com.tanhua.domain.vo.NearUserVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryVO;
import com.tanhua.domain.vo.RecommendUserVO;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author anshuai
 * @create 2021-01-29 17:58
 */
@Service
public class TanhuaService {

    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserLocationApi userLocationApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 今日佳人
     *
     * @return 用户详细信息
     */
    public ResponseEntity todayBest() {
        //- 使用UserHolder获取当前用户的id
        User user = UserHolder.getUser();

        // - 根据当前用户id，调用RecommendUserApi，查询缘分值最高的用户得到RecommendUser
        RecommendUser maxScoreUser = recommendUserApi.findMaxScoreUser(user.getId());
        if (maxScoreUser == null) {
            //如果查询到推荐的用户，就设置一个默认值
            maxScoreUser = new RecommendUser();
            maxScoreUser.setToUserId(user.getId());
            maxScoreUser.setUserId(11L);
            maxScoreUser.setScore(95D);
        }

        // - 根据RecommendUser的userId，查询得到这个用户的详细信息UserInfo
        UserInfo userInfo = userInfoApi.findById(maxScoreUser.getUserId());

        // - 把UserInfo转换成RecommendUserVO，响应给APP
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(userInfo.getTags().split(","));
        vo.setFateValue(maxScoreUser.getScore().intValue());

        return ResponseEntity.ok(vo);
    }

    /**
     * 交友-推荐
     * @param recommendUserQueryVO 用于接收请求封装的实体类也就是客户端发来的搜索条件
     * @return
     */
    public ResponseEntity recommendation(RecommendUserQueryVO recommendUserQueryVO) {

        //1. 获取当前用户id
        Long userId = UserHolder.getUserId();

        //2. 查询给userId推荐的好友 分页信息对象
        PageResult<RecommendUser> pageResult = recommendUserApi.recommendUserList(userId, recommendUserQueryVO.getPage(), recommendUserQueryVO.getPagesize());

        //3. 如果没有查询到，就设置默认值
        List<RecommendUser> recommendUserList = pageResult.getItems();

        //如果在mongodb数据库中查询不到给用户推荐的今日佳人数据,就构造假数据
        if (recommendUserList == null || recommendUserList.size() == 0){
            //创建集合用来装构造的假数据
            recommendUserList = new ArrayList<>();

            //准备一些用户id
            String ids = "2,3,4,5,6,7,8,9,10,11";
            for (String id : ids.split(",")) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(id));
                recommendUser.setScore(RandomUtils.nextDouble(70,98));
                //将准备好的数据添加到集合中
                recommendUserList.add(recommendUser);
            }

            pageResult = new PageResult<>(10,recommendUserQueryVO.getPagesize(),1,recommendUserQueryVO.getPage(),recommendUserList);
        }

        //4. 构造返回响应数据items,由实体类RecommendUserVO完成
        List<RecommendUserVO> volist = new ArrayList<>();
        for (RecommendUser recommendUser : pageResult.getItems()) {
            // 查询推荐用户的UserInfo
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

            //转换成RecommendUserVO
            RecommendUserVO vo = new RecommendUserVO();
            BeanUtils.copyProperties(userInfo,vo);

            if (userInfo.getTags() != null){
                vo.setTags(userInfo.getTags().split(","));
            }

            //设置缘分值
            vo.setFateValue(recommendUser.getScore().intValue());

            //存储到volist中
            volist.add(vo);
        }

        //5. 构造返回值
        PageResult<RecommendUserVO> result = new PageResult<>();
        BeanUtils.copyProperties(pageResult,result);
        result.setItems(volist);

        return ResponseEntity.ok(result);
    }

    /**
     * 查看佳人信息
     * @param targetUserId 佳人id
     * @return
     */
    public ResponseEntity findPersonalInfo(Long targetUserId) {

        //1.查询目标用户的详细信息
        UserInfo userInfo = userInfoApi.findById(targetUserId);

        //2.把结果转换成RecommendUserVO
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo,vo);
        vo.setTags(userInfo.getTags().split(","));

        //3. 需要查询目标用户和当前用户的缘分值
        Integer score = recommendUserApi.findRecommendScore(targetUserId, UserHolder.getUserId());
        vo.setFateValue(score);

        return ResponseEntity.ok(vo);

    }

    /**
     * 交友-查看佳人的陌生人问题
     * @param userId 佳人ID
     * @return
     */
    public ResponseEntity findStrangerQuestions(Long userId) {
        //查询佳人陌生人问题
        Question question = questionApi.findByUserId(userId);

        if (question == null) {
            return ResponseEntity.ok("你觉得我有什么优点呢?");
        }

        return ResponseEntity.ok(question.getTxt());
    }

    /**
     * 交友-回复对方的陌生人问题
     * @param targetUserId
     * @param reply
     * @return
     */
    public ResponseEntity replyStrangerQuestions(Long targetUserId, String reply) {
        //查询当前用户信息,需要发送消息人的头像昵称等信息
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        //查询陌生人问题
        Question question = questionApi.findByUserId(targetUserId);
        String questionText = question == null ? "你觉得我有什么优点呢?" : question.getTxt();

        //封装消息对象
        IMessage message = new IMessage();
        message.setNickname(userInfo.getNickname());
        message.setReply(reply);
        message.setUserId(UserHolder.getUserId().toString());
        message.setStrangerQuestion(questionText);

        //给对方发消息
        huanXinTemplate.sendMsg(targetUserId.toString(),message);

        return ResponseEntity.ok(null);
    }

    /**
     * 搜索附近的人
     * @param gender 要搜索的性别
     * @param distance 搜索的范围半径，单位是：米
     * @return
     */
    public ResponseEntity searchNear(String gender, Integer distance) {
        //1. 调用API，搜索附近的人
        List<UserLocationDTO> nearList = userLocationApi.searchNear(UserHolder.getUserId(), distance);

        //2. 循环剔除一些数据
        List<NearUserVO> voList = new ArrayList<>();
        for (UserLocationDTO dto : nearList) {
            //1.剔除自己
            if (dto.getUserId().longValue() == UserHolder.getUserId()){
                continue;
            }

            //2.剔除性别不符合的
            UserInfo userInfo = userInfoApi.findById(dto.getUserId());
            if (!"".equals(gender) && !userInfo.getGender().equals(gender)) {
                continue;
            }

            //3.添加到voList中
            NearUserVO vo = new NearUserVO();
            vo.setUserId(dto.getUserId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());

            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }

    /**
     * 左滑右滑
     * @return
     */
    public ResponseEntity cardsList() {
        //获取当前用户
        Long userId = UserHolder.getUserId();

        //调用api,查询推荐用户
        PageResult<RecommendUser> pageResult = recommendUserApi.recommendUserList(userId, 1, 10);
        //如果没有查询到,构造默认值
        List<RecommendUser> recommendUserList = pageResult.getItems();
        if (recommendUserList == null || recommendUserList.size() == 0) {
            recommendUserList = new ArrayList<>();
            String ids = "31,32,33,34,35,36,37,38,39,40";
            for (String id : ids.split(",")) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(id));
                recommendUser.setScore(RandomUtils.nextDouble(70, 98));
                recommendUserList.add(recommendUser);
            }

            pageResult = new PageResult<>(10,10, 1, 1, recommendUserList);
        }

        //4. 转换成RecommendUserVO列表
        List<RecommendUserVO> voList = new ArrayList<>();
        for (RecommendUser recommendUser : pageResult.getItems()) {
            // 查询推荐用户的UserInfo
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

            // 转换成RecommendUserVO
            RecommendUserVO vo = new RecommendUserVO();
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }

            // 设置缘分值
            vo.setFateValue(recommendUser.getScore().intValue());

            // 存储到voList里
            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }

    /**
     * 右滑喜欢
     * @param likeUserId 喜欢的用户Id
     * @return
     */
    public ResponseEntity love(Long likeUserId) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();

        userLikeApi.saveUserLike(userId, likeUserId);

        if (userLikeApi.isMutualLike(userId, likeUserId)) {
            //相互喜欢成为好友
            huanXinTemplate.addContactUser(userId,likeUserId);
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 左滑不喜欢
     * @param likeUserId 喜欢的用户id
     */
    public ResponseEntity disLikeUserId(Long likeUserId) {

        Long userId = UserHolder.getUserId();

        userLikeApi.delete(userId,likeUserId);

        return ResponseEntity.ok(null);
    }
}
